package com.lmx.tour_management_system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lmx.tour_management_system.mapper.AttractionsMapper;
import com.lmx.tour_management_system.pojo.Attraction;
import com.lmx.tour_management_system.pojo.Tourist;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lmx
 * @since 2021-01-11
 */
@Controller
public class AttractionsController {

    @Resource
    AttractionsMapper attractionsMapper;
    
    /**
     * 添加景点,上传图片
     * @param name
     * @param city
     * @param address
     * @param text
     * @param phone
     * @param contactor
     * @param cost
     * @param file 文件
     * @param model 
     * @return
     */
    @PostMapping("/admin/attraction/add")
    public String addAttraction(String name, String city, String address, String text, String phone, String contactor, int cost, MultipartFile file, Model model){

        Attraction attraction = new Attraction();

        if (file.isEmpty()) {
            model.addAttribute("msg","添加失败，请上传照片.");
            return "/admin/attractions_add";
        }

        String fileName = file.getOriginalFilename();
        String filePath = System.getProperty("user.dir")+"/target/classes/static/asserts/img_upload/";
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            attraction.setAttractionName(name);
            attraction.setAttractionCity(city);
            attraction.setAttractionText(text);
            attraction.setAttractionAddress(address);
            attraction.setAttractionPic(file.getOriginalFilename());
            attraction.setAttractionPhone(phone);
            attraction.setAttractionContacter(contactor);
            attraction.setAttractionCost(cost);
            attractionsMapper.insert(attraction);
            model.addAttribute("msg","上传成功.");
            return "/admin/attractions_add";
        } catch (IOException e) {
            e.printStackTrace();
            model.addAttribute("msg","上传失败！");
            return "/admin/attractions_add";
        }
    }

    /**
     * 跳转到景点更新页面
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/admin/attraction/toUpdate/{id}")
    public String toUpdateAttraction(@PathVariable("id") int id,Model model){
        Attraction attraction = attractionsMapper.selectOne(new QueryWrapper<Attraction>().eq("attraction_id", id));
        model.addAttribute("attraction",attraction);
        return "/admin/attractions_update";
    }

    @PostMapping("/admin/attraction/update")
    public String updateAttraction(Attraction attraction,MultipartFile file,Model model){

        System.out.println(attraction);
        System.out.println(file.getOriginalFilename());


        String filePath = System.getProperty("user.dir")+"/target/classes/static/asserts/img_upload/";

        try {
            if(!file.isEmpty()){
                String fileName = file.getOriginalFilename();
                File dest = new File(filePath + fileName);
                file.transferTo(dest);
                attraction.setAttractionPic(file.getOriginalFilename());
            }
            int i = attractionsMapper.updateById(attraction);
            if(i==1){
                model.addAttribute("msg","修改成功!");
            }else{
                model.addAttribute("msg","修改失败!");
            }
        }catch (Exception e){
            model.addAttribute("msg","系统异常");
            e.printStackTrace();
        }

        return "/admin/attractions_update";
    }


    @RequestMapping("/admin/attraction/query")
    public String queryAttraction(String serach,Model model){

        if(serach.trim().equals("")){
            model.addAttribute("msg","请输入搜索内容!");
            return "admin/attractions_query";
        }

        /**
         * 全局搜索
         */
        List<Attraction> attractions = attractionsMapper.selectList(new QueryWrapper<Attraction>().like("attraction_city", serach));
        attractions.addAll(attractionsMapper.selectList(new QueryWrapper<Attraction>().like("attraction_name", serach)));
        attractions.addAll(attractionsMapper.selectList(new QueryWrapper<Attraction>().like("attraction_address", serach)));

        /**
         * 每个字段查一次的方法可能会有重复数据
         * 通过Stream流去重
         */
        List<Attraction> result = new ArrayList<>();
        for (Attraction attraction : attractions) {
            boolean b = result.stream().anyMatch(a -> a.getAttractionId().equals(attraction.getAttractionId()));
            if (!b) {
                result.add(attraction);
            }
        }

        if(result.isEmpty()){
            model.addAttribute("msg","未查询到此景点!");
            return "admin/attractions_query";
        }

        model.addAttribute("attractions",result);
        return "admin/attractions_list";
    }


    /**
     * 根据ID删除景点 删除后再查一次.
     * @param id
     * @return
     */
    @RequestMapping("/admin/attraction/delete/{id}")
    public String deleteAttraction(@PathVariable("id") int id){
        int i = attractionsMapper.deleteById(id);
        return "redirect:/admin/toAttractionsList";
    }


    /**
     * 首页加载景点信息
     * @param model
     * @return
     */
    @RequestMapping("/")
    public String loadInfos(Model model, HttpSession session){
        List<Attraction> attractions = attractionsMapper.selectList(null);
        session.setAttribute("attractions",attractions);
        return "index";
    }


    @RequestMapping("/queryAttractionByCity/{cityName}")
    public String queryAttractionByCity(@PathVariable("cityName") String cityName,Model model){
        List<Attraction> attraction_list_byName = attractionsMapper.selectList(new QueryWrapper<Attraction>().eq("attraction_city", cityName));
        System.out.println(attraction_list_byName);
        model.addAttribute("list",attraction_list_byName);
        model.addAttribute("selected",cityName);
        return "forward:/toQuery";
    }

    @RequestMapping("/likeQueryAttraction")
    public String likeQueryAttraction(String search,Model model){

        if (search==null||search.equals("")){
            model.addAttribute("error","输入值不能为空!");
            return "forward:/";
        }

        List<Attraction> attraction_name_list = attractionsMapper.selectList(new QueryWrapper<Attraction>().like("attraction_name", search));
        List<Attraction> attraction_name_city = attractionsMapper.selectList(new QueryWrapper<Attraction>().like("attraction_city", search));

        attraction_name_list.addAll(attraction_name_city);

        HashSet hashSet = new HashSet(attraction_name_list);

        if(hashSet.isEmpty()){
            model.addAttribute("error","未查询到景点或城市!");
            return "forward:/";
        }

        model.addAttribute("list",hashSet);
        System.out.println(hashSet);
        return "query";

    }


}

